<?php
/**
 *
 * @category   babel 
 * @package    BABEL
 * @author     Hannes Magnusson <hannes.magnusson@gmail.com>
 * @copyright  2008 Team babel
 * @license    LGPL
 */


function babel_create_bogus_user($username) {
	$user = array(
		"bjori" => array(
			'external_app_id' => 10,
			'external_user_id' => 100002,
			'username' => 'bjori',
			'email' => 'hannes.magnusson@gmail.com',
			'profile' => array(
				'first_name' => 'Hannes',
				'last_name' => 'Magnusson',
			),
		),
		"sixpack" => array(
			'external_app_id' => 10,
			'external_user_id' => 100001,
			'username' => 'sixpack',
			'email' => 'sixpack@expono.com',
			'profile' => array(
				'first_name' => 'Joe',
				'last_name' => 'Sixpack',
			),
		),
		"deepo" => array(
			'external_app_id' => 10,
			'external_user_id' => 100003,
			'username' => 'deepo',
			'email' => 'hauknu@gmail.com',
			'profile' => array(
				'first_name' => 'Knut',
				'last_name' => 'Haug',
			),
		),
		"bakkefar" => array(
			'external_app_id' => 10,
			'external_user_id' => 100004,
			'username' => 'bakkefar',
			'email' => 'bakkefar@gmail.com',
			'profile' => array(
				'first_name' => 'Magnus',
				'last_name' => 'Bakke',
			),
		),
		"audis" => array(
			'external_app_id' => 10,
			'external_user_id' => 100005,
			'username' => 'audis',
			'email' => 'audun.skjelvan@gmail.com',
			'profile' => array(
				'first_name' => 'Audun',
				'last_name' => 'Skjelvan',
			),
		),
		"frankipus" => array(
			'external_app_id' => 10,
			'external_user_id' => 100006,
			'username' => 'frankipus',
			'email' => 'frank.bolviken@gmail.com',
			'profile' => array(
				'first_name' => 'Frank',
				'last_name' => 'Bølviken',
			),
		),
		"klb" => array(
			'external_app_id' => 10,
			'external_user_id' => 100007,
			'username' => 'klb',
			'email' => 'anders.bjornstad@gmail.com',
			'profile' => array(
				'first_name' => 'Anders',
				'last_name' => 'Bjørnstad',
			),
		),
	);

	if (!isset($user[$username])) {
		throw new Exception("Unknown username: $username");
	}

	return $user[$username];
}

function babel_login(array $user) {
	if ($user == null) {
		return babel_login_bogus();
	}

	$row = PDODB::execQueryFetch("SELECT user_id FROM babel_users WHERE external_app_id = ? AND external_user_id = ?", PDO::FETCH_COLUMN, array($user["external_app_id"],$user["external_user_id"]));

	if(empty($row)){
		$failed = !PDODB::execQuery("INSERT INTO babel_users (external_app_id, external_user_id, username, email, first_name, last_name, created, changed_date)
					VALUES(?,?,?,?,?,?,NOW(),NOW())",array($user["external_app_id"],$user["external_user_id"],$user["username"],$user["email"],$user["profile"]["first_name"],$user["profile"]["last_name"]),$id);
		if($failed){
			throw new Exception("Insert users query failed");
		}
	}
	else{
		$failed = !PDODB::execQuery("UPDATE babel_users SET changed_date = NOW() WHERE external_app_id = ? AND external_user_id = ?", array($user["external_app_id"],$user["external_user_id"]));
		if($failed){
			throw new Exception("Insert users query failed");
		}
	}

	$userrow = PDODB::execQueryFetch("SELECT * FROM babel_users u WHERE u.external_app_id = ? AND u.external_user_id = ?",PDO::FETCH_ASSOC, array($user["external_app_id"],$user["external_user_id"]));

	$failed = !PDODB::runQuery("SELECT * FROM babel_user_skills WHERE user_id = ?", array($userrow[0]["user_id"]), $stmt);
	if($failed){
			throw new Exception("Select users query failed");
	}

	$language = array();
	foreach($stmt as $row){
		$language[$row["language_id"]] = $row["skill"];
	}

	$nfo = $userrow[0];
	$_SESSION["user"] = array(
			'user_id' => $nfo["user_id"],
			'username' => $nfo["username"],
			'email' => $nfo["email"],
			'profile' => array(
				'first_name' => $nfo["first_name"],
				'last_name' => $nfo["last_name"],
				'active_language' => $nfo["language_id"],
				'language' => $language,
			),
		);
}

function babel_isAuthenticated($username, $token) {
	/* Temporary insert the token to our db while we authenticate the user */
	global $DB;
	$sql = "
INSERT INTO
	babel_tokens (
		timestamp,
		username,
		token
	) VALUES(
		NOW(),
		?,
		?
	)
";
	$stmt = $DB->prepare($sql);
	$rsl = $DB->execute($stmt, array($username, $token));
	if ($rsl instanceof DB_Error || $rsl != DB_OK) {
		throw new Exception("DB Query failure, sorry");
	}

	$posts = http_build_query(array("username" => $username, "token" => $token));
	$opts = array(
		"method" => "POST",
		"content" => $posts,
	);

	$ctx = stream_context_create(array("http" => $opts));
	$content = file_get_contents(EXPONO_AUTH_URL, null, $ctx);
	list($version, $status, $msg) = explode(' ',$http_response_header[0], 3);
	if ($status_code != 200) {
		throw new Exception("Cannot contact Expono authentication API.. {$status}:{$msg}");
	}

	$user = unserialize($content);
	if (!is_array($user)) {
		throw Exception("Unexpected data received from Expono authentication API..");
	}

	$sql = "DELETE FROM babel_tokens WHERE token=?";
	$stmt = $DB->prepare($sql);
	/* NOTE: Ignore the results, have no meaning for us anyway */
	$DB->execute($stmt, $token);

	return $user;
}

